package com.ruoyi.web.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.wx.WxMaConfiguration;
import com.ruoyi.common.core.controller.ApiBaseController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TokenUtils;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.domain.SysToken;
import com.ruoyi.system.service.IMemberService;
import com.ruoyi.system.service.ISysTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 账号管理Controller
 */
@Api(description = "帐号管理")
@Controller
@RequestMapping("/api/account")
public class ApiAccountController extends ApiBaseController {

    @Autowired
    IMemberService memberService;

    @Autowired
    ISysTokenService sysTokenService;

    @PostMapping("/login")
    @ResponseBody
    public ApiResult login(@RequestBody JSONObject jsonObject)
    {
        String code = jsonObject.get("code").toString();
        JSONObject userInfoData = jsonObject.getJSONObject("userInfo");
        //JSONObject userInfo = userInfoData.getJSONObject("userInfo");

        if (StringUtils.isBlank(code)) {
            return ApiResult.error("code 为空 登录失败");
        }

        final WxMaService wxService = WxMaConfiguration.getMaService();
        String encryptedData = userInfoData.getString("encryptedData");
        //微信登录
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        if (session == null){
            return ApiResult.error("获取用户信息失败");
        }

        String sessionKey = session.getSessionKey();
        String signature = userInfoData.getString("signature");
        String rawData = userInfoData.getString("rawData");
        String iv = userInfoData.getString("iv");
        this.logger.info(session.getOpenid());

        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return ApiResult.error("验证失败");
        }

        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        //判断这个用户是否是新用户
        Member member =  memberService.selectMemberByOpenId(userInfo.getOpenId());
        if (member == null){
            //是新用户 开始创建
            member = new Member();
            member.setOpenId(userInfo.getOpenId());
            member.setUsername(URLEncoder.encode(userInfo.getNickName()));
            member.setBalance(BigDecimal.ZERO.doubleValue());
            member.setAmount(BigDecimal.ZERO.doubleValue());
            member.setIsLocked(false);
            member.setLockedDate(null);
            member.setMemberRankId(0L);
            member.setAvatar(userInfo.getAvatarUrl());
            member.setNickname(URLEncoder.encode(userInfo.getNickName()));
            member.setGender(0L);
            member.setAddress(userInfo.getCity());
            member.setLoginDate(new Date());
            memberService.insertMember(member);
        }else{
            //老用户 更新
            member.setAvatar(userInfo.getAvatarUrl());
            member.setNickname(URLEncoder.encode(userInfo.getNickName()));
            member.setUsername(URLEncoder.encode(userInfo.getNickName()));
            member.setGender(0L);
            member.setAddress(userInfo.getCity());
            member.setLoginDate(new Date());
            memberService.updateMember(member);
        }

        //更新token
        SysToken sysToken = sysTokenService.selectSysTokenByMemberId(member.getId());
        if (sysToken == null){
            //生成一个新的token
            sysToken = new SysToken();
            sysToken.setToken(TokenUtils.generateToken());
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DAY_OF_MONTH, 20); // 今天+20天
            Date expired_date = c.getTime();
            sysToken.setExpiredDate(expired_date);
            sysToken.setMemberId(member.getId());
            sysTokenService.insertSysToken(sysToken);
        }else{
            sysToken.setToken(TokenUtils.generateToken());
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DAY_OF_MONTH, 20); // 今天+20天
            Date expired_date = c.getTime();
            sysToken.setExpiredDate(expired_date);
            sysTokenService.updateSysToken(sysToken);
        }

        String strToken = sysToken.getToken();
        JSONObject resultJson = new JSONObject();
        resultJson.put("token",strToken );
        return ApiResult.success("登录成功", resultJson);
    }
}
